import {
  searchPriceAsceBookByKeyWords,
  searchPriceDescBookByKeyWords,
  searchNewBookByKeyWords,
  searchHotBookByKeyWords,
  searchUser,
  followUser,
  unFollowUser
} from "@/Api/search";
const state = {
  searchList: [],//搜索到的书籍列表
  searchUserList:[]//搜索到的用户列表
};
const mutations = {
  SET_SEARCH_USER_LIST(state,list){
    state.searchUserList=list
  },
  SET_SEARCH_LIST(state, list) {
    state.searchList = list;
  },
  UPDATE_SEARCH_USER_TRUE(state,index){
    state.searchUserList[index].fansNum+=1
    state.searchUserList[index].isFollow=true
  },
  UPDATE_SEARCH_USER_FALSE(state,index){
    state.searchUserList[index].fansNum-=1
    state.searchUserList[index].isFollow=false
  },
};
const actions = {
  async unFollowUser(context,index){
  console.log('取消关注')
  let id=context.state.searchUserList[index].id
    console.log(id)
      let result=await unFollowUser(id)
      console.log(result)
      if(result.data.status==200)
      {
        context.commit('UPDATE_SEARCH_USER_FALSE',index)
        return 'success'
      }else{
        return 'error'
      }
    },
 async followUser(context,index){
  console.log('关注')
    let id=context.state.searchUserList[index].id
    console.log(id)
    let result=await followUser(id)
      console.log(result)
      if(result.data.status==200)
    {
      context.commit('UPDATE_SEARCH_USER_TRUE',index)
      return 'success'
    }else{
      return 'error'
    }
  },
  // 搜索用户
  async searchUser({commit},keyword){
    let result =await searchUser(keyword)
    console.log(result)
    if(result.data.status==200){
      commit('SET_SEARCH_USER_LIST',result.data.data)
    }else{
      commit('SET_SEARCH_USER_LIST',[])
    }
  },
  //获取最新的搜索列表
  async searchNewList({ commit }, keyword) {
    let result = await searchNewBookByKeyWords(keyword);
    if (result.data.status == 200) {
      commit("SET_SEARCH_LIST", result.data.data);
    }else{
      commit("SET_SEARCH_LIST", []);
    }
  },
  //获取最热的搜索列表
  async searchHotList({ commit }, keyWord) {
    let result = await searchHotBookByKeyWords(keyWord);
    console.log(result);
    if (result.data.status == 200) {
      commit("SET_SEARCH_LIST", result.data.data);
    }
  },
  //获取最价格升序的搜索列表
  async searchPriceAsecList({ commit }, keyWord) {
    let result = await searchPriceAsceBookByKeyWords(keyWord);
    if (result.data.status == 200) {
      commit("SET_SEARCH_LIST", result.data.data);
    }
  },
  //获取价格降序的搜索列表
  async searchPriceDescList({ commit }, keyWord) {
    let result = await searchPriceDescBookByKeyWords(keyWord);
    if (result.data.status == 200) {
      commit("SET_SEARCH_LIST", result.data.data);
    }
  },
};
const getters = {
  searchResult(state) {
    return state.searchList || [];
  },
  userList(state){
    return state.searchUserList||[]
  }
};
export default {
  state,
  mutations,
  actions,
  getters,
};
